package com.example.freeengine.wallpaper.alarm;

import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import com.bumptech.glide.Glide;
import com.example.freeengine.wallpaper.constants.WallPaperConstant;
import com.example.freeengine.wallpaper.constants.WallPaperUpdateStrategy;
import com.example.freeengine.wallpaper.fragment.PictureInfo;
import com.example.freeengine.wallpaper.fragment.everydayrefresh.picturesource.BingPictureSource;
import com.example.freeengine.wallpaper.network.VolleyCallback;
import com.example.freeengine.wallpaper.persistence.entity.WallPaperCycleRefreshAlbumItem;
import com.example.freeengine.wallpaper.persistence.repository.WallPaperCycleRefreshRepository;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;

/**
 * @author Terry Deng
 */
public class MyAlarmWorkerReceiver extends BroadcastReceiver {
    private static final String TAG = MyAlarmWorkerReceiver.class.getSimpleName();
    WallpaperManager wallpaperManager;
    WallPaperCycleRefreshRepository wallPaperCycleRefreshRepository;
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(TAG, "alarm worker receive broadcast...");
        String strategy = intent.getStringExtra(WallPaperConstant.KEY_ALARM_WORKER_RECEIVER_EXTRA_STRATEGY);
        wallpaperManager = WallpaperManager.getInstance(context);

        if (strategy.equals(WallPaperUpdateStrategy.FROM_EVERYDAY.name())){
            Log.i(TAG, "start do work everyday...");

            saveEverydayRefreshPicture(context,
                    context.getFilesDir() + WallPaperConstant.WALLPAPER_EVERYDATREFRESH_BING_HISTORY_FILE_PATH);

            Log.i(TAG, "work end everyday...");
        } else if(strategy.equals(WallPaperUpdateStrategy.FROM_CYCLEREFRESH.name())){
            Log.i(TAG, "start do work cycle refresh...");

            wallPaperCycleRefreshRepository = new WallPaperCycleRefreshRepository(context);
            WallPaperCycleRefreshAlbumItem nextCycleRefreshAlbumItem = getNextCycleRefreshAlbumItem(wallPaperCycleRefreshRepository, getCycleRefreshAlbumInfo(context),
                    getCycleRefreshAlbumItemInfo(context));
            setWallPaper(nextCycleRefreshAlbumItem.getPicturePath());
            setCycleRefreshAlbumItemInfo(context, nextCycleRefreshAlbumItem.getId());

            Log.i(TAG, "work end cycle refresh...");
        }

        setWallPaperWallPaperAlarmWakeupTime(context, generateWakeupTime());
    }

    public void setWallPaper(String path){
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        try {
            wallpaperManager.setBitmap(bitmap);
            Log.i(TAG, "onStartCommand: " + "wallpaper set ok");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void saveEverydayRefreshPicture(Context context, String path){
        BingPictureSource.generatePictureUrl(context, new VolleyCallback() {
            @Override
            public void onSuccess(String newRequest) {

                String wallPaperEveryDayRefreshCurrentFlag = getWallPaperEveryDayRefreshCurrentFlag(context);
                if (wallPaperEveryDayRefreshCurrentFlag.equals(newRequest)){
                    // 如果已经下载过了，不再下载
                    Log.i(TAG, "onSuccess: " + "having download: " + newRequest);
                    // 设置壁纸
                    List<PictureInfo> everydayRefreshHistoryPictures = getEverydayRefreshHistoryPictures(path);
                    if (!everydayRefreshHistoryPictures.isEmpty()){
                        setWallPaper(everydayRefreshHistoryPictures.get(0).getPath());
                    }
                    return;
                }
                try {
                    // 当前图片
                    File file = Glide.with(context).downloadOnly().load(newRequest).submit().get();
                    File dstDir = new File(path);
                    if (!dstDir.exists()) {
                        dstDir.mkdirs();
                    }
                    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
                    String imageFileName = "JPEG_" + timeStamp + "_" + ".jpeg";
                    File dstFile = new File(dstDir, imageFileName);
                    if (!dstFile.exists()) {
                        dstFile.createNewFile();
                    }
                    try (InputStream is = new FileInputStream(file);
                         OutputStream os = new FileOutputStream(dstFile)) {
                        byte[] fData = new byte[1024];
                        int len = 0;
                        while ((len = is.read(fData)) > 0) {
                            os.write(fData, 0, len);
                        }
                        setWallPaperEveryDayRefreshCurrentFlag(context, newRequest);
                        setWallPaper(dstFile.getAbsolutePath());
                    }
                } catch (ExecutionException | IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public String getWallPaperEveryDayRefreshCurrentFlag(Context context){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getString(WallPaperConstant.KEY_SHP_WALLPAPER_EVERYDATREFRESH_CURRENT_FLAG, "0");
    }
    public void setWallPaperEveryDayRefreshCurrentFlag(Context context, String url){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(WallPaperConstant.KEY_SHP_WALLPAPER_EVERYDATREFRESH_CURRENT_FLAG, url);
        edit.apply();
    }
    public List<PictureInfo> getEverydayRefreshHistoryPictures(String path){
        List<PictureInfo> pictureInfos = new ArrayList<>();
        TreeSet<File> fileTreeSet = new TreeSet<>((o1, o2) -> {
            // 必须使用三种情况
            if (o1.lastModified() - o2.lastModified() == 0) {
                return 0;
            }
            if (o1.lastModified() - o2.lastModified() < 0) {
                return 1;
            }
            return -1;
        });
        Log.i("wallpaper path",  path);
        File imagesDir = new File(path);
        if (!imagesDir.exists()) {
            return pictureInfos;
        }

        File[] files = imagesDir.listFiles();
        if (files != null && files.length > 0){
            for (File f : files){
                if (f.isFile()){
                    fileTreeSet.add(f);
                }
            }
        }

        fileTreeSet.forEach(f -> {
            PictureInfo pictureInfo = new PictureInfo();
            pictureInfo.setPath(f.getAbsolutePath());
            pictureInfos.add(pictureInfo);
        });

        return pictureInfos;
    }


    public WallPaperCycleRefreshAlbumItem getNextCycleRefreshAlbumItem(WallPaperCycleRefreshRepository wallPaperCycleRefreshRepository,
                                                                       Long albumId, Long currentItemId){
        try {
            List<WallPaperCycleRefreshAlbumItem> wallPaperCycleRefreshAlbumItemList = wallPaperCycleRefreshRepository.findAllByAlbumId(albumId);
            for (WallPaperCycleRefreshAlbumItem wallPaperCycleRefreshAlbumItem : wallPaperCycleRefreshAlbumItemList){
                if (wallPaperCycleRefreshAlbumItem.getId() > currentItemId){
                    return wallPaperCycleRefreshAlbumItem;
                }
            }
            // 循环
            return wallPaperCycleRefreshAlbumItemList.get(0);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return new WallPaperCycleRefreshAlbumItem();
    }

    public Long getCycleRefreshAlbumInfo(Context context){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getLong(WallPaperConstant.KEY_SHP_WALLPAPER_CURRENT_CYCLEREFRESH_ALBUM_INFO, 0);
    }

    public Long getCycleRefreshAlbumItemInfo(Context context){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        return sharedPreferences.getLong(WallPaperConstant.KEY_SHP_WALLPAPER_CURRENT_PICTURE_INFO, 0);
    }

    public void setCycleRefreshAlbumItemInfo(Context context, Long id){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putLong(WallPaperConstant.KEY_SHP_WALLPAPER_CURRENT_PICTURE_INFO, id);
        edit.apply();
    }

    public static String generateWakeupTime(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.setTimeZone(TimeZone.getTimeZone("Asia/Chongqing"));

        return new SimpleDateFormat().format(calendar.getTime());
    }

    public void setWallPaperWallPaperAlarmWakeupTime(Context context, String time){
        SharedPreferences sharedPreferences = context.getSharedPreferences(WallPaperConstant.SHP_WALLPAPER_FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(WallPaperConstant.KEY_ALARM_WAKEUP_TIME, time);
        edit.apply();
    }

}
